/************************************************
 * Author       :   XXY
 * Blog         :   https://www.cnblogs.com/jzyl
 * Gitee        :   https://gitee.com/xiaobaichong
 * Email        :   1047185209@QQ.com
 * FileName     :   SmoothTrackPathEditor.cs
 * CreateData   :   2023/11/28 20:52:29
 * UnityVersion :   2021.3.30f1c1
 * Description  :   SmoothTrackPath Editor
************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif
using UnityEngine;

namespace Main
{
#if UNITY_EDITOR
    [CustomEditor(typeof(SmoothTrackPath))]
    public class SmoothTrackPathEditor : TrackPathEditor<SmoothTrackPath>
    {
        private ReorderableList mWaypointList;

        /// <summary>Get the property names to exclude in the inspector.</summary>
        /// <param name="excluded">Add the names to this list</param>
        protected override void GetExcludedPropertiesInInspector(List<string> excluded)
        {
            base.GetExcludedPropertiesInInspector(excluded);
            excluded.Add(FieldPath(x => x.m_Waypoints));
        }

        void OnEnable()
        {
            mWaypointList = null;
        }


        // ReSharper disable once UnusedMember.Global - magic method called when doing Frame Selected
        public bool HasFrameBounds()
        {
            return Target.m_Waypoints != null && Target.m_Waypoints.Length > 0;
        }

        // ReSharper disable once UnusedMember.Global - magic method called when doing Frame Selected
        public Bounds OnGetFrameBounds()
        {
            Vector3[] wp;
            int selected = mWaypointList == null ? -1 : mWaypointList.index;
            if (selected >= 0 && selected < Target.m_Waypoints.Length)
                wp = new Vector3[1] { Target.m_Waypoints[selected].position };
            else
                wp = Target.m_Waypoints.Select(p => p.position).ToArray();
            return GeometryUtility.CalculateBounds(wp, Target.transform.localToWorldMatrix);
        }

        public override void OnInspectorGUI()
        {
            BeginInspector();
            if (mWaypointList == null)
                SetupWaypointList();

            if (mWaypointList.index >= mWaypointList.count)
                mWaypointList.index = mWaypointList.count - 1;

            // Ordinary properties
            DrawRemainingPropertiesInInspector();

            // Path length
            EditorGUILayout.LabelField("Path Length", Target.PathLength.ToString());

            // Waypoints
            EditorGUI.BeginChangeCheck();
            mWaypointList.DoLayoutList();
            if (EditorGUI.EndChangeCheck())
                serializedObject.ApplyModifiedProperties();
        }

        void SetupWaypointList()
        {
            mWaypointList = new ReorderableList(
                    serializedObject, FindProperty(x => x.m_Waypoints),
                    true, true, true, true);

            mWaypointList.drawHeaderCallback = (Rect rect) =>
            { EditorGUI.LabelField(rect, "Waypoints"); };

            mWaypointList.drawElementCallback
                = (Rect rect, int index, bool isActive, bool isFocused) =>
                { DrawWaypointEditor(rect, index); };

            mWaypointList.onAddCallback = (ReorderableList l) =>
            { InsertWaypointAtIndex(l.index); };
        }

        void DrawWaypointEditor(Rect rect, int index)
        {
            // Needed for accessing string names of fields
            SmoothTrackPath.Waypoint def = new SmoothTrackPath.Waypoint();
            SerializedProperty element = mWaypointList.serializedProperty.GetArrayElementAtIndex(index);

            float hSpace = 3;
            rect.width -= hSpace; rect.y += 1;
            Vector2 numberDimension = GUI.skin.label.CalcSize(new GUIContent("999"));
            Rect r = new Rect(rect.position, numberDimension);
            if (GUI.Button(r, new GUIContent(index.ToString(), "Go to the waypoint in the scene view")))
            {
                if (SceneView.lastActiveSceneView != null)
                {
                    mWaypointList.index = index;
                    SceneView.lastActiveSceneView.pivot = Target.EvaluatePosition(index);
                    SceneView.lastActiveSceneView.size = 4;
                    SceneView.lastActiveSceneView.Repaint();
                }
            }

            float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2f;
            GUIContent rollLabel = new GUIContent("Roll");
            Vector2 labelDimension = GUI.skin.label.CalcSize(rollLabel);
            float rollWidth = labelDimension.x + floatFieldWidth;
            r.x += r.width + hSpace; r.width = rect.width - (r.width + hSpace + rollWidth) - (r.height + hSpace);
            EditorGUI.PropertyField(r, FindPropertyRelative(element, () => def.position), GUIContent.none);

            r.x += r.width + hSpace; r.width = rollWidth;
            float oldWidth = EditorGUIUtility.labelWidth;
            EditorGUIUtility.labelWidth = labelDimension.x;

            var indent = EditorGUI.indentLevel;
            EditorGUI.indentLevel = 0;
            EditorGUI.PropertyField(r, FindPropertyRelative(element, () => def.roll), rollLabel);
            EditorGUIUtility.labelWidth = oldWidth;
            EditorGUI.indentLevel = indent;

            r.x += r.width + hSpace; r.height += 1; r.width = r.height;
            GUIContent setButtonContent = EditorGUIUtility.IconContent("d_RectTransform Icon");
            setButtonContent.tooltip = "Set to scene-view camera position";
            if (GUI.Button(r, setButtonContent, GUI.skin.label) && SceneView.lastActiveSceneView != null)
            {
                Undo.RecordObject(Target, "Set waypoint");
                SmoothTrackPath.Waypoint wp = Target.m_Waypoints[index];
                Vector3 pos = SceneView.lastActiveSceneView.camera.transform.position;
                wp.position = Target.transform.InverseTransformPoint(pos);
                Target.m_Waypoints[index] = wp;
            }
        }

        void InsertWaypointAtIndex(int indexA)
        {
            Vector3 pos = Vector3.right;
            float roll = 0;

            // Get new values from the current indexA (if any)
            int numWaypoints = Target.m_Waypoints.Length;
            if (indexA < 0)
                indexA = numWaypoints - 1;
            if (indexA >= 0)
            {
                int indexB = indexA + 1;
                if (Target.m_Looped && indexB >= numWaypoints)
                    indexB = 0;
                if (indexB >= numWaypoints)
                {
                    Vector3 delta = Vector3.right;
                    if (indexA > 0)
                        delta = Target.m_Waypoints[indexA].position - Target.m_Waypoints[indexA - 1].position;
                    pos = Target.m_Waypoints[indexA].position + delta;
                    roll = Target.m_Waypoints[indexA].roll;
                }
                else
                {
                    // Interpolate
                    pos = Target.transform.InverseTransformPoint(Target.EvaluatePosition(0.5f + indexA));
                    roll = Mathf.Lerp(Target.m_Waypoints[indexA].roll, Target.m_Waypoints[indexB].roll, 0.5f);
                }
            }
            Undo.RecordObject(Target, "Add waypoint");
            var wp = new SmoothTrackPath.Waypoint();
            wp.position = pos;
            wp.roll = roll;
            var list = new List<SmoothTrackPath.Waypoint>(Target.m_Waypoints);
            list.Insert(indexA + 1, wp);
            Target.m_Waypoints = list.ToArray();
            Target.InvalidateDistanceCache();
            RepaintGameView();
            mWaypointList.index = indexA + 1; // select it
        }

        void OnSceneGUI()
        {
            if (mWaypointList == null)
                SetupWaypointList();

            if (Tools.current == Tool.Move)
            {
                Color colorOld = Handles.color;
                var localToWorld = Target.transform.localToWorldMatrix;
                for (int i = 0; i < Target.m_Waypoints.Length; ++i)
                {
                    DrawSelectionHandle(i, localToWorld);
                    if (mWaypointList.index == i)
                        DrawPositionControl(i, localToWorld, Target.transform.rotation); // Waypoint is selected
                }
                Handles.color = colorOld;
            }
        }

        void DrawSelectionHandle(int i, Matrix4x4 localToWorld)
        {
            if (Event.current.button != 1)
            {
                Vector3 pos = localToWorld.MultiplyPoint(Target.m_Waypoints[i].position);
                float size = HandleUtility.GetHandleSize(pos) * 0.2f;
                Handles.color = Color.white;
                if (Handles.Button(pos, Quaternion.identity, size, size, Handles.SphereHandleCap)
                    && mWaypointList.index != i)
                {
                    mWaypointList.index = i;
                    RepaintGameView();
                }
                // Label it
                Handles.BeginGUI();
                Vector2 labelSize = new Vector2(
                        EditorGUIUtility.singleLineHeight * 2, EditorGUIUtility.singleLineHeight);
                Vector2 labelPos = HandleUtility.WorldToGUIPoint(pos);
                labelPos.y -= labelSize.y / 2;
                labelPos.x -= labelSize.x / 2;
                GUILayout.BeginArea(new Rect(labelPos, labelSize));
                GUIStyle style = new GUIStyle();
                style.normal.textColor = Color.black;
                style.alignment = TextAnchor.MiddleCenter;
                GUILayout.Label(new GUIContent(i.ToString(), "Waypoint " + i), style);
                GUILayout.EndArea();
                Handles.EndGUI();
            }
        }

        void DrawPositionControl(int i, Matrix4x4 localToWorld, Quaternion localRotation)
        {
            SmoothTrackPath.Waypoint wp = Target.m_Waypoints[i];
            Vector3 pos = localToWorld.MultiplyPoint(wp.position);
            EditorGUI.BeginChangeCheck();
            Handles.color = Target.m_Appearance.pathColor;
            Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
                ? localRotation : Quaternion.identity;
            float size = HandleUtility.GetHandleSize(pos) * 0.1f;
            Handles.SphereHandleCap(0, pos, rotation, size, EventType.Repaint);
            pos = Handles.PositionHandle(pos, rotation);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(target, "Move Waypoint");
                wp.position = Matrix4x4.Inverse(localToWorld).MultiplyPoint(pos);
                Target.m_Waypoints[i] = wp;
                Target.InvalidateDistanceCache();
                RepaintGameView();
            }
        }

        [DrawGizmo(GizmoType.Active | GizmoType.NotInSelectionHierarchy
             | GizmoType.InSelectionHierarchy | GizmoType.Pickable, typeof(SmoothTrackPath))]
        static void DrawGizmos(SmoothTrackPath path, GizmoType selectionType)
        {
            var isActive = Selection.activeGameObject == path.gameObject;
            DrawPathGizmo(path,
                isActive ? path.m_Appearance.pathColor : path.m_Appearance.inactivePathColor, isActive);
        }
        private static int m_lastRepaintFrame;
        public static void DrawPathGizmo(PathBase path, Color pathColor, bool isActive)
        {
            // Draw the path
            Color colorOld = Gizmos.color;
            Gizmos.color = pathColor;
            float step = 1f / path.m_Resolution;
            float halfWidth = path.m_Appearance.width * 0.5f;
            Vector3 lastPos = path.EvaluatePosition(path.MinPos);
            Vector3 lastW = (path.EvaluateOrientation(path.MinPos)
                             * Vector3.right) * halfWidth;
            float tEnd = path.MaxPos + step / 2;
            for (float t = path.MinPos + step; t <= tEnd; t += step)
            {
                Vector3 p = path.EvaluatePosition(t);
                if (!isActive || halfWidth == 0)
                {
                    Gizmos.DrawLine(p, lastPos);
                }
                else
                {
                    Quaternion q = path.EvaluateOrientation(t);
                    Vector3 w = (q * Vector3.right) * halfWidth;
                    Vector3 w2 = w * 1.2f;
                    Vector3 p0 = p - w2;
                    Vector3 p1 = p + w2;
                    Gizmos.DrawLine(p0, p1);
                    Gizmos.DrawLine(lastPos - lastW, p - w);
                    Gizmos.DrawLine(lastPos + lastW, p + w);
#if false
                    // Show the normals, for debugging
                    Gizmos.color = Color.red;
                    Vector3 y = (q * Vector3.up) * halfWidth;
                    Gizmos.DrawLine(p, p + y);
                    Gizmos.color = pathColor;
#endif
                    lastW = w;
                }

                lastPos = p;
            }
            Gizmos.color = colorOld;
        }
        /// <summary>
        /// Force a repaint of the Game View
        /// </summary>
        /// <param name="unused">Like it says</param>
        public static void RepaintGameView(UnityEngine.Object unused = null)
        {
            if (m_lastRepaintFrame == Time.frameCount)
                return;
            m_lastRepaintFrame = Time.frameCount;

            EditorApplication.QueuePlayerLoopUpdate();
            UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
        }
        /// <summary>
        /// A compiler-assisted (non-string-based) way to call SerializedProperty.FindPropertyRelative
        /// </summary>
        /// <param name="obj">The serialized object to search</param>
        /// <param name="exp">Magic expression that resolves to a field: () => myClass.m_MyField</param>
        /// <returns>The resulting SerializedProperty, or null</returns>
        public SerializedProperty FindPropertyRelative(SerializedProperty obj, Expression<Func<object>> exp)
        {
            return obj.FindPropertyRelative(PropertyName(exp));
        }
        /// <summary>
        /// This is a way to get a field name string in such a manner that the compiler will
        /// generate errors for invalid fields.  Much better than directly using strings.
        /// Usage: instead of
        /// <code>
        /// "m_MyField";
        /// </code>
        /// do this:
        /// <code>
        /// MyClass myclass = null;
        /// SerializedPropertyHelper.PropertyName( () => myClass.m_MyField);
        /// </code>
        /// </summary>
        /// <param name="exp">Magic expression that resolves to a field: () => myClass.m_MyField</param>
        /// <returns></returns>
        public static string PropertyName(Expression<Func<object>> exp)
        {
            var body = exp.Body as MemberExpression;
            if (body == null)
            {
                var ubody = (UnaryExpression)exp.Body;
                body = ubody.Operand as MemberExpression;
            }
            return body.Member.Name;
        }
    }
    /// <summary>
    /// A convenience base class for making inspector editors.
    /// </summary>
    /// <typeparam name="T">The class we're editing</typeparam>
    public class TrackPathEditor<T> : UnityEditor.Editor where T : class
    {
        /// <summary>
        /// The target object, cast as the same class as the object being edited
        /// </summary>
        protected T Target { get { return target as T; } }

        /// <summary>
        /// Return the Serialized property for a field, and exclude it from being automatically 
        /// displayed in the inspector.  Call this when you need to provide a custom UX for a field.
        /// </summary>
        /// <typeparam name="TValue">Magic experssion code</typeparam>
        /// <param name="expr">Call format is FindAndExcludeProperty(x => x.myField)</param>
        /// <returns>The serialized property for the field</returns>
        protected SerializedProperty FindAndExcludeProperty<TValue>(Expression<Func<T, TValue>> expr)
        {
            SerializedProperty p = FindProperty(expr);
            ExcludeProperty(p.name);
            return p;
        }

        /// <summary>
        /// Return the Serialized property for a field.
        /// </summary>
        /// <typeparam name="TValue">Magic experssion code</typeparam>
        /// <param name="expr">Call format is FindProperty(x => x.myField)</param>
        /// <returns>The serialized property for the field</returns>
        protected SerializedProperty FindProperty<TValue>(Expression<Func<T, TValue>> expr)
        {
            return serializedObject.FindProperty(FieldPath(expr));
        }

        /// <summary>
        /// Magic code to get the string name of a field.  Will not build if the field name changes.
        /// </summary>
        /// <typeparam name="TValue">Magic experssion code</typeparam>
        /// <param name="expr">Call format is FieldPath(x => x.myField)</param>
        /// <returns>The string name of the field</returns>
        protected string FieldPath<TValue>(Expression<Func<T, TValue>> expr)
        {
            return GetFieldPath(expr);
        }

        /// <summary>Obsolete, do not use.  Use the overload, which is more performant</summary>
        /// <returns>List of property names to exclude</returns>
        protected virtual List<string> GetExcludedPropertiesInInspector() { return mExcluded; }

        /// <summary>Get the property names to exclude in the inspector.</summary>
        /// <param name="excluded">Add the names to this list</param>
        protected virtual void GetExcludedPropertiesInInspector(List<string> excluded)
        {
            excluded.Add("m_Script");
        }

        /// <summary>
        /// Exclude a property from automatic inclusion in the inspector 
        /// when DrawRemainingPropertiesInInspector() is called
        /// </summary>
        /// <param name="propertyName">The property to exclude</param>
        protected void ExcludeProperty(string propertyName)
        {
            mExcluded.Add(propertyName);
        }

        /// <summary>Check whenther a property is in the excluded list</summary>
        /// <param name="propertyName">The property to check</param>
        /// <returns>True if property is excluded from automatic inclusion in the inspector 
        /// when DrawRemainingPropertiesInInspector() is called</returns>
        protected bool IsPropertyExcluded(string propertyName)
        {
            return mExcluded.Contains(propertyName);
        }

        /// <summary>
        /// Draw the inspector
        /// </summary>
        public override void OnInspectorGUI()
        {
            BeginInspector();
            DrawRemainingPropertiesInInspector();
        }

        List<string> mExcluded = new List<string>();

        /// <summary>
        /// Clients should call this at the start of OnInspectorGUI.  
        /// Updates the serialized object and Sets up for excluded properties.
        /// </summary>
        protected virtual void BeginInspector()
        {
            serializedObject.Update();
            mExcluded.Clear();
            GetExcludedPropertiesInInspector(mExcluded);
        }

        /// <summary>
        /// Draw a property in the inspector, if it is not excluded.  
        /// Property is marked as drawn, so will not be drawn again 
        /// by DrawRemainingPropertiesInInspector()
        /// </summary>
        /// <param name="p">The property to draw</param>
        protected virtual void DrawPropertyInInspector(SerializedProperty p)
        {
            if (!IsPropertyExcluded(p.name))
            {
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(p);
                if (EditorGUI.EndChangeCheck())
                    serializedObject.ApplyModifiedProperties();
                ExcludeProperty(p.name);
            }
        }

        /// <summary>
        /// Draw all remaining unexcluded undrawn properties in the inspector.
        /// </summary>
        protected void DrawRemainingPropertiesInInspector()
        {
            EditorGUI.BeginChangeCheck();
            DrawPropertiesExcluding(serializedObject, mExcluded.ToArray());
            if (EditorGUI.EndChangeCheck())
                serializedObject.ApplyModifiedProperties();
        }


        /// <summary>Returns a string path from an expression - mostly used to retrieve serialized properties
        /// without hardcoding the field path. Safer, and allows for proper refactoring.</summary>
        /// <typeparam name="TType">Magic expression</typeparam>
        /// <typeparam name="TValue">Magic expression</typeparam>
        /// <param name="expr">Magic expression</param>
        /// <returns>The string version of the field path</returns>
        public static string GetFieldPath<TType, TValue>(Expression<Func<TType, TValue>> expr)
        {
            MemberExpression me;
            switch (expr.Body.NodeType)
            {
                case ExpressionType.MemberAccess:
                    me = expr.Body as MemberExpression;
                    break;
                default:
                    throw new InvalidOperationException();
            }

            var members = new List<string>();
            while (me != null)
            {
                members.Add(me.Member.Name);
                me = me.Expression as MemberExpression;
            }

            var sb = new StringBuilder();
            for (int i = members.Count - 1; i >= 0; i--)
            {
                sb.Append(members[i]);
                if (i > 0) sb.Append('.');
            }
            return sb.ToString();
        }
    }
#endif
}
